from PIL import Image  
import os  
  
def crop_image_to_32x32(image_folder, output_folder):  
    # 确保输出文件夹存在  
    if not os.path.exists(output_folder):  
        os.makedirs(output_folder)  
  
    # 遍历图片文件夹中的所有文件  
    for filename in os.listdir(image_folder):  
        if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):  # 检查文件扩展名  
            image_path = os.path.join(image_folder, filename)  
            image = Image.open(image_path)  
  
            # 计算水平和垂直方向上可以裁剪成多少个32x32的块  
            horizontal_parts = image.width // 32  
            vertical_parts = image.height // 32  
  
            # 遍历每个块并裁剪  
            for h in range(vertical_parts):  
                for w in range(horizontal_parts):  
                    left = w * 32  
                    upper = h * 32  
                    right = left + 32  
                    lower = upper + 32  
  
                    box = (left, upper, right, lower)  
                    cropped_image = image.crop(box)  
  
                    # 保存裁剪后的图像  
                    cropped_image_path = os.path.join(output_folder, f'{filename[:-4]}_{h}_{w}.png')  # 假设输出为PNG格式  
                    cropped_image.save(cropped_image_path)  
  
            # （可选）处理剩余部分  
            # ...（与之前相同，但通常这里你可能不需要为每个文件都重复这部分逻辑） 
            # 如果图片尺寸不是32的倍数，则处理剩余的部分（可选）  
    # 注意：这里只处理了水平方向，垂直方向同理  
    remainder_width = image.width % 32  
    if remainder_width > 0:  
        for h in range(vertical_parts):  
            left = horizontal_parts * 32  
            upper = h * 32  
            right = left + remainder_width  
            lower = upper + 32  
              
            box = (left, upper, right, lower)  
            cropped_image = image.crop(box)  
            cropped_image_path = os.path.join(output_folder, f'remainder_h_{h}.png')  
            cropped_image.save(cropped_image_path)   
  
# 获取脚本文件所在目录  
script_dir = os.path.dirname(os.path.abspath(__file__))  
# 导航到上一级目录中的data文件夹  
data_folder = os.path.join(script_dir, '..', 'data','source_data')  
# 设置输出文件夹  
output_folder = os.path.join(script_dir, 'cropped_images')  
  
# 调用函数  
crop_image_to_32x32(data_folder, output_folder)